#!/usr/bin/env python
#coding:utf-8

__author__ = "Dabin Chung"

import web,twitUtil

try:
    from google.appengine.ext import db
except:
    pass
    
try:
    from urlparse import parse_qs, parse_qsl
except ImportError:
    from cgi import parse_qs, parse_qsl    

render = web.template.render('templates/')

urls = ('/', 'index','/add','add','/refresh','refresh','/auth','auth')
app = web.application(urls, globals())
#application = app.wsgifunc()# for uwsgi

def clear_store():
    tokens = db.GqlQuery("SELECT * FROM Token")
    if tokens:
        results = tokens.fetch(1)
        if results:
            db.delete(results)#delete

class Token(db.Model):#gql class
    ot = db.StringProperty(multiline=True)
    ots = db.StringProperty(multiline=True)
    ss = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class index: 
    def GET(self):   
        web.header('Content-Type','text/html; charset=utf-8', unique=True)               
        i = web.input(oauth_verifier=None)
        
        try:#callback,update token,secret
            credentials = {}
            tokens = db.GqlQuery("SELECT * FROM Token")
            results = tokens.fetch(1)
            token = results[0]
            if token.ss == '0':
                credentials['oauth_token'] = token.ot
                credentials['oauth_token_secret'] = token.ots
                access_token = twitUtil.get_access_token(credentials,i.oauth_verifier)
                token.ot = access_token['oauth_token']#update token
                token.ots = access_token['oauth_token_secret']#update secret
                token.ss = '1'
                token.put()
        except Exception,e:
            pass
        return render.twittest([])

class auth:
    def POST(self):
        web.header('Content-Type','text/html; charset=utf-8', unique=True)
        str1 = ''
        try:
            credentials,str1 = twitUtil.get_auth_url()
            clear_store()
            t1 = Token()
            t1.ot = credentials['oauth_token']
            t1.ots = credentials['oauth_token_secret']
            t1.ss = '0'
            t1.put()#save
        except Exception,e:
            str1 = str1 + ' ' + str(e)
        return '<div>' + str1 + '</div>'
        
class refresh:
    def POST(self):
        i = web.input()    
        web.header('Content-Type','text/html; charset=utf-8', unique=True)       
        access_token = {}
        try:
            tokens = db.GqlQuery("SELECT * FROM Token")
            token = tokens.fetch(1)[0]
            if token.ss == '1':
                access_token['oauth_token'] = token.ot
                access_token['oauth_token_secret'] = token.ots
                tts,lasthash = twitUtil.GetHomeTimelinelist(access_token,'20',False,i.lasttthash)
                return str(render.ttstreams(tts)) + '<div id="lastthash">' + lasthash + '</div>'
        except Exception,e:
            return str(render.ttstreams([])) + '<div id="lastthash">' + str(i.lasttthash) + '</div>'
        #raise web.seeother('/')
        
                

class add:
    def POST(self):
        i = web.input()
        web.header('Content-Type','text/html; charset=utf-8', unique=True)
        access_token = {}
        message = ''
        try:            
            tokens = db.GqlQuery("SELECT * FROM Token")
            token = tokens.fetch(1)[0]
            if token.ss == '1':
                access_token['oauth_token'] = token.ot
                access_token['oauth_token_secret'] = token.ots
                message = twitUtil.UpdateStatus(access_token,i.status.encode('utf-8'))
        except Exception,e:
            message = message + ' ' + str(e)

        return message

class api1:
    def POST(self):
        pass
        return ''
    
    def GET(self):
        pass
        return ''    
        
class api2:
    def POST(self):
        pass
        return ''
    
    def GET(self):
        pass
        return ''      

class api3:
    def POST(self):
        pass
        return ''
    
    def GET(self):
        pass
        return ''         
        
if __name__=="__main__":
    #web.internalerror = web.debugerror #debug
    #app.run() #common
    pass
    main = app.cgirun()#for gae


